package org.pku_uestc.hackathon.bean;

import java.util.LinkedList;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.pku_uestc.hackathon.utils.HTTPRequestHelper;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public abstract class Sensor {

	public static final int TYPE_TEMPHUMI = 0;
	public static final int TYPE_TEMPERATURE = 1;
	public static final int TYPE_AIRQUALITY = 2;
	public static final int TYPE_HUMIDITY = 3;
	public static final int TYPE_SMARTLIGHT = 4;
	
	public static final int TYPE_SIZE = 5;

	public static String token = null;

	protected List<ISensorHandler> list;

	protected Sensor() {
		if (token == null)
			init();
	}

	@SuppressLint("HandlerLeak")
	private void init() {
		this.performPostRequest(
				new Handler() {
					@Override
					public void handleMessage(Message msg) {
						if(token != null)
							return;
						
						JSONTokener jsonParser = new JSONTokener(msg.getData()
								.getString("RESPONSE"));
						try {
							JSONObject data = (JSONObject) jsonParser
									.nextValue();
							String success = data.getString("success");
							if (success.equals("true")) {
								token = data.getString("auth_token");
								Log.d(getClass().getName(), "auth success "+token);
							}

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				},
				"https://huantengsmart.com/users/sign_in.json",
				"{\"user\":{\"email\":\"hackathon2@huantengsmart.com\",\"password\":\"h4o9ba\"}}");
	}

	/**
	 * 返回传感器类型
	 * 
	 * @return
	 */
	public abstract int getType();
	
	/**
	 * 获取灯的id
	 * 
	 * @return
	 */
	public abstract int getId();
	
	/**
	 * 请求数据
	 * 
	 * @return
	 */
	public abstract void request(int timer);

	public void setHandler(List<ISensorHandler> list) {
		this.list = list;
	}

	public void addHandler(ISensorHandler handler) {
		if (this.list == null)
			this.list = new LinkedList<ISensorHandler>();
		if (this.list.contains(handler))
			return;
		this.list.add(handler);
	}

	public void removeHandler(ISensorHandler handler) {
		this.list.remove(handler);
	}

	protected void performPostRequest(final Handler handler, final String url,
			final String data) {
		new Thread(){
			@Override
			public void run(){
				HttpClient client = new DefaultHttpClient();
				HttpPost post = new HttpPost(url);

				try {
					StringEntity s = new StringEntity(data);
					s.setContentEncoding("UTF-8");
					s.setContentType("application/json");
					post.setEntity(s);

					client.execute(post,
							HTTPRequestHelper.getResponseHandlerInstance(handler));
				} catch (Exception e) {
					Log.e("Sensor", "performPostRequest"+e.getStackTrace());
				}
			}
		}.start();
	}

	protected void performPutRequest(final Handler handler, final String url,
			final String data) {
		new Thread(){
			@Override
			public void run(){
				HttpClient client = new DefaultHttpClient();
				HttpPut post = new HttpPut(url);
				try {
					StringEntity s = new StringEntity(data);
					s.setContentEncoding("UTF-8");
					s.setContentType("application/json");
					post.setEntity(s);

					client.execute(post,
							HTTPRequestHelper.getResponseHandlerInstance(handler));
				} catch (Exception e) {
					Log.e("Sensor", "performPutRequest"+e.getStackTrace());
				}
			}
		}.start();
	}

	protected void preformGetRequest(final Handler handler, final String url) {
		new Thread(){
			@Override
			public void run(){
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				get.addHeader("Content-type", "application/json");
				get.addHeader("Content-encoding", "UTF-8");
				try {
					client.execute(get,
							HTTPRequestHelper.getResponseHandlerInstance(handler));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					Log.e("Sensor", "performGetRequest"+e.getStackTrace());
				}
			}
		}.start();
	}
	
	@Override
	public boolean equals(Object o){
		if(o instanceof Sensor){
			Sensor other = (Sensor)o;
			if(other.getId() == getId()
					&& other.getType() == getType()){
				return true;
			}
		}
		return false;
	}
	
	@Override
	public int hashCode() {
		return getId()*100+getType();
	}
	
	@Override
	public String toString(){
		return ""+(getId()*100+getType());
	}
}
